# from django.contrib import admin
#
# from .models import Publisher, Author, Book
#
#
# # admin.site.register(Publisher)
# # admin.site.register(Author)
# # admin.site.register(Book)
#
# # admin.site.register((Publisher, Author, Book))
#
# class AuthorAdmin(admin.ModelAdmin):
#     list_display = ('first_name', 'last_name', 'email')
#     search_fields = ('first_name', 'last_name')
#
#
# class BookAdmin(admin.ModelAdmin):
#     list_display = ('title', 'publisher', 'publication_date')
#     list_filter = ('publication_date',)
#     date_hierarchy = 'publication_date'
#     ordering = ('-publication_date',)  # - 按降序排
#     # fields = ('title', 'authors', 'publisher') # 编辑表单
#     filter_horizontal = ('authors',) # 横向
#     # filter_vertical = ('authors',) # 纵向的 filter_horizontal
#     raw_id_fields = ('publisher',)
#
#
# admin.site.register(Publisher)
# admin.site.register(Author, AuthorAdmin)
# admin.site.register(Book, BookAdmin)

from django.contrib import admin
from django.db.models import Model

from .models import *

local_dict = locals()

filter_field_list = ['DateTimeField', 'BooleanField']
search_fields_exclude_list = ['ForeignKey', 'OneToOneField']


class ModelField:
    def __init__(self, c):
        d = self.get_list_dict(c)
        self.list_filter = d.get('filter')
        self.search_fields = d.get('search')
        self.list_display = d.get('display')
        self.verbose_name_list = d.get('verbose_name')

    def get_list_dict(self, c):
        list_filter = []
        search_fields = []
        list_display = []
        for f in c._meta.fields:
            f_t_name = f.__class__.__name__
            f_name = f.name
            list_display.append(f_name)
            if f_t_name not in search_fields_exclude_list:
                search_fields.append(f_name)

            if f_t_name in filter_field_list:
                list_filter.append(f_name)

        return {'filter': list_filter, 'search': search_fields, 'display': list_display, }


def get_model_list():
    for k in list(local_dict.keys()):
        c = local_dict[k]
        try:
            if issubclass(c, Model) and c != Model:
                yield c
        except TypeError:
            continue


def get_admin_by_model(m):
    model_field = ModelField(m)
    attrs = {
        'list_display': model_field.list_display,
        'search_fields': model_field.search_fields,
        'list_filter': model_field.list_filter
    }
    return type(m.__name__ + 'Admin', (admin.ModelAdmin,), attrs)


for m in get_model_list():
    admin.site.register(m, get_admin_by_model(m))
